package com.api.gbhg.huangwm.action;

import com.alibaba.fastjson.JSONObject;
import com.api.gbhg.huangwm.dao.YuSuanTiaoZhengDao;
import com.customization.commons.LogTool;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2022-07-04
 * @Version 1.0
 * @Description TODO 预算调整流程（经济分类调整、预算减少）时记录uf_jingfei和uf_jingfeilaiyuan的版本数据
 **/
public class YsJingFeiVersionCopy implements Action {
    private LogTool logTool = new LogTool("/log/gbhg/huangwm/action/YsJingFeiVersionCopy",false);
    private YuSuanTiaoZhengDao dao = new YuSuanTiaoZhengDao();

    private static String YJ ;//科目级别
    private static String XJ ;//科目下级

    @Override
    public String execute(RequestInfo requestInfo) {
        return JingFeiVersionCopy(requestInfo);
    }

    public String JingFeiVersionCopy(RequestInfo requestInfo){
        int requestid = requestInfo.getRequestManager().getRequestid();
        int billid = requestInfo.getRequestManager().getBillid();
        String tablename = requestInfo.getRequestManager().getBillTableName();
        int formid = requestInfo.getRequestManager().getFormid();

        BaseBean baseBean = new BaseBean();
        YJ = baseBean.getPropValue("Verification","yj");
        XJ = baseBean.getPropValue("Verification","xj");
        logTool.writeLog("财政拨款核批层级 YJ="+YJ+"  XJ="+XJ);
        String flowtype = "";
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        for(Property property : properties){
            if(property.getName().equals("flowtype")){
                flowtype = property.getValue();
            }
        }
        if(flowtype.equals("") || flowtype.equals("null")){
            requestInfo.getRequestManager().setMessagecontent("同步经费额度版本数据异常 未获取到表单flowtype");
            requestInfo.getRequestManager().setMessageid(requestid+"");
            return FAILURE_AND_CONTINUE;
        }
        try{
            String JJFL = dao.getJjfl_DtTablesNoZSXM(formid);//获取细化经济分类明细表名称
            List<String> HPQD = dao.getHpqd_DtTablesNoZSXM(formid);//获取核批渠道明细表名称

            RecordSet rs = new RecordSet();
            String sql1 = "select dzlx,dzxm,lcbj,ysnd,sydw,sbdw,xmmc,jbr from "+tablename+" where id="+billid;
            rs.execute(sql1);
            rs.next();
            int dzlx = rs.getInt("dzlx");
            String dzxm = Util.null2String(rs.getString("dzxm"));
            String lcbj = Util.null2String(rs.getString("lcbj"));
            String ysnd = Util.null2String(rs.getString("ysnd"));
            String sydw = Util.null2String(rs.getString("sydw"));
            String sbdw = Util.null2String(rs.getString("sbdw"));
            String xmmc = Util.null2String(rs.getString("xmmc"));
            String jbr = Util.null2String(rs.getString("jbr"));
            rs.executeUpdate("delete from uf_jingfeiVersion where lcjlid=?",requestid);
            rs.executeUpdate("delete from uf_jingfeilaiyuanVersion where lcid=?",requestid);
            RecordSet exits = new RecordSet();
            if(dzlx!=1){
                RecordSetTrans rst = new RecordSetTrans();
                rst.setAutoCommit(false);
                exits.execute("select isnull(max(version) ,0) version from uf_jingfeiVersion where lcjlid="+dzxm);
                if(exits.next() && exits.getCounts()>=1){
                    int version = exits.getInt("version");
                    if(version<=0){
                        requestInfo.getRequestManager().setMessageid(requestid+"");
                        requestInfo.getRequestManager().setMessagecontent("当前调整项目未获取到[uf_jingfeiVersion]表数据");
                        return FAILURE_AND_CONTINUE;
                    }
                    int newVersion = version+1;
                    String jingfei = "INSERT INTO [dbo].[uf_jingfeiVersion]\n" +
                            "           ([requestId],[ybx],[sydw],[lcbj],[lcjlid],[bmzcjjfl],[zfjjfl],[nd],[ze],[syed],[dj],[sbdw],[xmmc],[gkdw],[version],[tzlc])\n" +
                            "select [requestId],[ybx],[sydw],[lcbj],[lcjlid],[bmzcjjfl],[zfjjfl],[nd],[ze],[syed],[dj],[sbdw],[xmmc],[gkdw]," +newVersion+","+requestid+"\n"+
                            "from uf_jingfeiVersion where lcjlid="+dzxm +" and version="+version;
                    String jingfeilaiyuan = "INSERT INTO [dbo].[uf_jingfeilaiyuanVersion]\n" +
                            "           ([requestId],[sbdw],[lcbj],[nd],[gnkm],[yslylx],[dfczbkxm],[zyczbkxm],[je],[syed],[djje],[lcid],[zcqd],[zyczbksr],[lylx],[srlx],[version],[tzlc])\n" +
                            "select [requestId],[sbdw],[lcbj],[nd],[gnkm],[yslylx],[dfczbkxm],[zyczbkxm],[je],[syed],[djje],[lcid],[zcqd],[zyczbksr],[lylx],[srlx]," +newVersion+","+requestid+"\n"+
                            "from uf_jingfeilaiyuanVersion where lcid="+dzxm +" and version="+version;
                    logTool.writeLog("jingfei："+jingfei);
                    logTool.writeLog("jingfeilaiyuan："+jingfeilaiyuan);
                    try {
                        boolean r1 = rst.execute(jingfei);
                        boolean r2 = rst.execute(jingfeilaiyuan);
                        if(!r1 || !r2){
                            requestInfo.getRequestManager().setMessageid(requestid+"");
                            requestInfo.getRequestManager().setMessagecontent("记录经费额度版本数据SQL异常");
                            return FAILURE_AND_CONTINUE;
                        }
                        rst.commit();
                    }catch (Exception e){
                        rst.rollback();
                        requestInfo.getRequestManager().setMessageid(requestid+"");
                        requestInfo.getRequestManager().setMessagecontent("记录经费额度版本数据SQL异常");
                        return FAILURE_AND_CONTINUE;
                    }
                }else {
                    requestInfo.getRequestManager().setMessageid(requestid+"");
                    requestInfo.getRequestManager().setMessagecontent("当前调整项目未获取到[uf_jingfeiVersion]表数据");
                    return FAILURE_AND_CONTINUE;
                }
            }else{
                boolean JFVersion = dao.jingFeiVersionTableValues(tablename,requestid+"");
                if(!JFVersion){
                    requestInfo.getRequestManager().setMessagecontent("同步经费额度版本数据异常 生成jingfei_version表出错");
                    requestInfo.getRequestManager().setMessageid(requestid+"");
                    return FAILURE_AND_CONTINUE;
                }
                //预算追加 新插入数据
                dao.deleteJingFeiByRequestid(requestid+"");
                RecordSet getJF = new RecordSet();
                getJF.execute("select * from "+JJFL+" where mainid="+billid);
                boolean flag1 = false;
                Map<String, String> map = new HashMap<>();
                while (getJF.next()) {
                    map.put("requestId", requestid+"");
                    map.put("lcbj", lcbj);
                    map.put("lcjlid", requestid+"");
                    map.put("nd", ysnd);//预算年度
                    map.put("ze", getJF.getStringNoTrim("hjwy"));
                    map.put("bmzcjjfl", getJF.getStringNoTrim("bmyszcjjfl"));
                    map.put("zfjjfl", getJF.getStringNoTrim("dyzfjjfl"));
                    map.put("gkdw","");
                    map.put("sydw",sydw);
                    String syed = "0.00";
                    if (getJF.getStringNoTrim("hjwy").equals("")) {
                        map.put("ze", "0.00");
                        syed = "0.00";
                    } else {
                        syed = getJF.getStringNoTrim("hjwy");
                    }
                    map.put("syed", syed);
                    map.put("dj", "0.00");
                    map.put("sbdw", sbdw);
                    map.put("xmmc", xmmc);
                    map.put("modedatamodifier", jbr);
                    map.put("modedatamodifydatetime", TimeUtil.getCurrentTimeString());//当前日期时间
                    logTool.writeLog("经费入库："+ JSONObject.toJSONString(map));
                    flag1 = dao.insertBudgeLines(map);
                }
                if(!flag1){
                    requestInfo.getRequestManager().setMessageid(requestid+"");
                    requestInfo.getRequestManager().setMessagecontent("生成经费额度失败");
                    return FAILURE_AND_CONTINUE;
                }
                //获取上年结转和当年预算的明细数据
                RecordSet snjz = new RecordSet();
                snjz.execute("select * from "+HPQD.get(1) +" where mainid="+billid);
                RecordSet dnys = new RecordSet();
                dnys.execute("select * from "+HPQD.get(0) +" where mainid="+billid);

                Map<String, Object>[] maps = new HashMap[snjz.getArray().size() + dnys.getArray().size()];
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);//当前年份
                int year1 = calendar.get(Calendar.YEAR);//上年年份
                int count = 0;

                // 上年结转核批明细
                while (snjz.next()) {
                    int sum1 = 0;
                    int sum2 = 0;
                    maps[count] = new HashMap<>();
                    //支出渠道
                    String zcqd = snjz.getString("zcqd");
                    //收入类型
                    String srlx = snjz.getString("srlx");
                    //功能科目_新
                    String gnkm = "";
                    //中央财政拨款项目
                    String zyczbksr = snjz.getString("zyczbksr");
                    //地方财政拨款项目上年结转
                    String dfczbkxmsnjz = snjz.getString("dfczbkxmsnjz");
                    if (srlx.equals("0")) {//0：中央
                        if (StringUtils.isNotBlank(zyczbksr)) {
                            String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                            sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                            sum2 = Integer.parseInt(sta[1]);//表id
                            if (sum1 == Integer.parseInt(YJ)) {
                                gnkm = dao.getSubjectsGnkm(sum2);
                            } else if (sum1 == Integer.parseInt(XJ)) {
                                gnkm = dao.getSubjectsGnkm(dao.getSubjectsGnkm2(sum2));
                            }
                        }
                    } else if (srlx.equals("1")) {//1:非中央
                        RecordSet getGnkm = dao.theCentral(zcqd, year, sbdw);
                        gnkm = getGnkm.getString("gnkm");
                    }
                    logTool.writeLog("上年--收入类型:" + srlx + "功能科目:" + gnkm + "sum1" + sum1 + "sum2" + sum2);

                    //核批金额
                    String hpje = snjz.getString("hpje");
                    maps[count].put("sbdw", sbdw);
                    maps[count].put("nd", ysnd);
                    //来源类型
                    maps[count].put("zcqd", zcqd);
                    //功能科目
                    maps[count].put("gnkm", gnkm);
                    //金额
                    maps[count].put("je", hpje);
                    //剩余额度
                    maps[count].put("syed", hpje);
                    //冻结金额
                    maps[count].put("djje", 0);
                    //预算来源类型
                    maps[count].put("yslylx", "上年结转核批");
                    //收入类型
                    maps[count].put("srlx", srlx);
                    //地方财政拨款项目上年结转
                    maps[count].put("dfczbkxm", dfczbkxmsnjz);
                    //中央财政拨款收入
                    maps[count].put("zyczbksr", zyczbksr);
                    maps[count].put("lcid", requestid);
                    count++;
                }


                // 当年预算核批明细
                while (dnys.next()) {
                    int sum1 = 0;
                    int sum2 = 0;
                    maps[count] = new HashMap<>();
                    //支出渠道
                    String zcqd = dnys.getString("zcqd");
                    //收入类型
                    String srlx = dnys.getString("srlx");
                    //功能科目_新
                    String gnkm = "";
                    //中央财政拨款收入
                    String zyczbksr = dnys.getString("zyczbksr");
                    //地方财政拨款项目当年预算
                    String dfczbkxmdnys = dnys.getString("dfczbkxmdnys");
                    if (srlx.equals("0")) {//0：中央
                        if (StringUtils.isNotBlank(zyczbksr)) {
                            String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                            sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                            sum2 = Integer.parseInt(sta[1]);//表id
                            if (sum1 == Integer.parseInt(YJ)) {
                                gnkm = dao.getSubjectsGnkm(sum2);
                            } else if (sum1 == Integer.parseInt(XJ)) {
                                gnkm = dao.getSubjectsGnkm(dao.getSubjectsGnkm2(sum2));
                            }
                        }
                    } else if (srlx.equals("1")) {//1:非中央
                        RecordSet getGNkm = dao.theCentral(zcqd, year1, sbdw);
                        getGNkm.next();
                        gnkm = getGNkm.getString("gnkm");
                    }
                    logTool.writeLog("当年--收入类型:" + srlx + "功能科目:" + gnkm + "sum1" + sum1 + "sum2" + sum2);
                    //核批金额
                    String hpje = dnys.getString("hpje");
                    maps[count].put("sbdw", sbdw);
                    maps[count].put("nd", ysnd);
                    //来源类型
                    maps[count].put("zcqd", zcqd);
                    //功能科目
                    maps[count].put("gnkm", gnkm);
                    //金额
                    maps[count].put("je", hpje);
                    //剩余额度
                    maps[count].put("syed", hpje);
                    //冻结金额
                    maps[count].put("djje", 0);
                    //预算来源类型
                    maps[count].put("yslylx", "当年预算核批");
                    //收入类型
                    maps[count].put("srlx", srlx);
                    //地方财政拨款项目当年预算
                    maps[count].put("dfczbkxm", dfczbkxmdnys);
                    //中央财政拨款收入
                    maps[count].put("zyczbksr", zyczbksr);
                    maps[count].put("lcid", requestid);
                    count++;
                }

                if (maps.length > 0) {
                    RecordSet rss = new RecordSet();
                    rss.executeUpdate("delete from uf_jingfeilaiyuan where lcid =" + requestid);
                    rss.executeUpdate("delete from uf_jingfeilaiyuanVersion where lcid =" + requestid);

                    //存储数据到经费来源表
                    boolean b = dao.storageDateToJingfeiLy(maps);
                    if (!b) {
                        logTool.writeLog("同步核批渠道到经费来源表错误");
                        requestInfo.getRequestManager().setMessagecontent("同步核批渠道到经费来源表错误");
                        requestInfo.getRequestManager().setMessageid(requestid+"");
                        return FAILURE_AND_CONTINUE;
                    }else{
                        String jingfei = "INSERT INTO [dbo].[uf_jingfeiVersion]\n" +
                                "           ([requestId],[ybx],[sydw],[lcbj],[lcjlid],[bmzcjjfl],[zfjjfl],[nd],[ze],[syed],[dj],[sbdw],[xmmc],[gkdw],[version])\n" +
                                "select [requestId],[ybx],[sydw],[lcbj],[lcjlid],[bmzcjjfl],[zfjjfl],[nd],[ze],[syed],[dj],[sbdw],[xmmc],[gkdw]," +1+"\n"+
                                "from uf_jingfei where lcjlid="+requestid;
                        String jingfeilaiyuan = "INSERT INTO [dbo].[uf_jingfeilaiyuanVersion]\n" +
                                "           ([requestId],[sbdw],[lcbj],[nd],[gnkm],[yslylx],[dfczbkxm],[zyczbkxm],[je],[syed],[djje],[lcid],[zcqd],[zyczbksr],[lylx],[srlx],[version])\n" +
                                "select [requestId],[sbdw],[lcbj],[nd],[gnkm],[yslylx],[dfczbkxm],[zyczbkxm],[je],[syed],[djje],[lcid],[zcqd],[zyczbksr],[lylx],[srlx]," +1+"\n"+
                                "from uf_jingfeilaiyuan where lcid="+requestid;
                        rss.executeUpdate(jingfei);
                        rss.executeUpdate(jingfeilaiyuan);
                    }
                }

                return SUCCESS;
            }
        }catch (Exception e){
            requestInfo.getRequestManager().setMessagecontent("同步经费额度版本数据异常 "+e.getMessage());
            requestInfo.getRequestManager().setMessageid(requestid+"");
            return FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }
}
